package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Permission;
import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.util.RequiredPermission;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IPermissionService permissionService;

    @Autowired
    private IRoleService roleService;

    @RequestMapping("/list")
    public String list(Model model, QueryObject qo) {
        PageInfo<Role> pageInfo = roleService.query(qo);
        model.addAttribute("pageInfo", pageInfo);

        return "/role/list";
    }

    @RequestMapping("/input")
    public String input(Long id, Model model) {
        //如果id不等于空,查询数据给回显
        if (id != null) {
            Role role = roleService.get(id);
            //给回显数据role
            model.addAttribute("role", role);
            //查询改id的所有权限并给与回显
           List<Permission> perList =  permissionService.getPermissions(id);
           model.addAttribute("perList",perList);
        }
        //查询全部权限信息带回去
        List<Permission> permissions = permissionService.getList();
        model.addAttribute("permissions",permissions);
        return "/role/input";
    }

    @RequiredPermission(name = "角色更新/增加",expression="role.saveOrUpdate")
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Role role,Long[] ids) {
//            id不为null,为修改;
        if (role.getId() != null) {
            roleService.update(role,ids);
        } else{
            roleService.save(role,ids);

        }
        return "redirect:/role/list";
    }

    @RequiredPermission(name = "角色删除",expression="role.delete")
    @RequestMapping("/delete")
    public String delete(Long id){
        if(id!=null){
            roleService.delete(id);
        }
        return "redirect:/role/list";
    }
}
